package cn.wolfcode.user.servlet;

import cn.wolfcode.user.entity.User;
import cn.wolfcode.user.service.UserService;
import cn.wolfcode.user.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * @author 李新雨的项目86176
 * @version 1.0
 * @date 2024-10-30 22:35
 */
//// TODO: 2024/11/8 只能注册普通账户
@WebServlet("/register")
@MultipartConfig(maxFileSize = 5000000)
public class UserRegisterServlet extends HttpServlet {
    private final UserService userService=new UserServiceImpl();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        Part headImg = req.getPart("headImg");
        String realName = headImg.getSubmittedFileName();
        String suffix = realName.substring(realName.indexOf('.'));
        String newName=  UUID.randomUUID().toString()+ suffix;
        String path=req.getServletContext().getRealPath("image/")+newName;
        User user=new User();
        //查询所有的用户名
        List<String> userNames=userService.selAllUserName();
        for (String userName1 : userNames) {
            if (username.equals(userName1)){
                req.setAttribute("msgs","用户已经存在");
                req.getRequestDispatcher("/register.jsp").forward(req,resp);
            }
        }
        user.setUsername(username);
        user.setPassword(password);
        user.setHeadImg("image/"+newName);
        /**
         * 安全退出
         */
        req.getSession().setAttribute("USER_SESSION",user);
        userService.insertInto(user);
        headImg.write(path);
        resp.sendRedirect("/login.jsp");
    }
}
